/**
 * @param file: 文件流
 * @Date 2020-07-08
*/

export function compressImage(file) {
    return new Promise(resolve => {
        // 如果文件小于1Mb 则不进行压缩
        if (file.size / 1024 / 1024 <= 1) {
            resolve(file)
        } else {
            const image = new Image()
            image.src = URL.createObjectURL(file)
            image.onload = function () {
                let w = image.width
                let h = image.height
                let nw = w > 1024 ? 1024 : w
                let nh = parseInt(nw / w * h)
                // 生成canvas
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                // 创建属性节点
                const anw = document.createAttribute('width')
                anw.nodeValue = nw
                const anh = document.createAttribute('height')
                anh.nodeValue = nh
                canvas.setAttributeNode(anw)
                canvas.setAttributeNode(anh)
                ctx.drawImage(this, 0, 0, nw, nh)
                // 图像质量
                let quality = 0.9
                // quality值越小，所绘制出的图像越模糊
                let data = canvas.toDataURL(file.type || 'image/jpeg', quality)
                // 压缩完成执行回调
                let newFile = convertBase64UrlToBlob(data)
                //循环压缩直到大小不超过1Mb
                while (newFile.size / 1024 / 1024 > 1 && quality > 0.1) {
                    quality -= 0.1
                    data = canvas.toDataURL(file.type || 'image/jpeg', quality)
                    newFile = convertBase64UrlToBlob(data)
                }
                resolve(newFile)
            }
        }
    });
}

/**
 * @Description: 转换base64格式
 * @param urlData : 图片rul
 * @Date 2020-07-13
*/
function convertBase64UrlToBlob(urlData) {
    const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
    // 处理异常,将ascii码小于0的转换为大于0
    const ab = new ArrayBuffer(bytes.length)
    const ia = new Uint8Array(ab)
    for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
    }
    return new Blob([ab], { type: 'image/png' })
}
